<?
if (!defined("LEVEL") || LEVEL < 30 || !defined("OK")) { header('location: ?home'); }
echo "<pre>";
print_r($_POST);
echo "</pre>";

if (isset($url['d']) && isnum($url['d']) && $url['d'] > 0) { 
	$sql = mysql_query1("SELECT `file`, `foto` FROM `siuntiniai` WHERE `ID` = ".escape((int)$url['d'])." LIMIT 1");
	$row = mysql_fetch_assoc($sql);
	if (isset($row['file']) && !empty($row['file'])) { trink("downloads/".$row['file']); }
	if (isset($row['foto']) && !empty($row['foto'])) { trink("images/downloads/".$row['foto']); }
	mysql_query1("DELETE FROM `siuntiniai` WHERE (`ID`=".escape((int)$url['d']).")");
	if (mysql_affected_rows() > 0) { msg("Ištrintas","Siuntinys sėkmingai ištrintas"); }
	else { klaida("Klaida","Siuntinio trinimo klaida"); }
}
if(isset($_POST['Submit']) && $_POST['Submit'] == "Siųsti" && isset($_FILES)) {
	if (is_uploaded_file($_FILES['file']['tmp_name'])) {
		if (isset($_FILES['file']) && !empty($_FILES['file'])) { 
			upload("file",array("jpg","bmp","png","psd","zip","rar","mrc","dll"), 1048576, "downloads/");
			//if (is_uploaded_file($_FILES['pic']['tmp_name'])) { upload("pic",array("jpg","bmp","png","psd","zip","rar","mrc","dll"), 1048576, "downloads/"); }
		}
	}
}

function upload($file,$file_types_array=array("JPG","PNG","PSD","ZIP"), $max_file_size=1048576, $upload_dir="downloads") {
	if($_FILES["$file"]["name"]!="") {
		$origfilename = $_FILES["$file"]["name"];
		$filename = explode(".", $_FILES["$file"]["name"]);
		$filenameext = strtolower($filename[count($filename)-1]);
		unset($filename[count($filename)-1]);
		$filename = implode(".", $filename);
		$filename = substr($filename, 0, 60).".".$filenameext;
		$file_ext_allow = FALSE;
		for($x=0;$x<count($file_types_array);$x++) {
			if($filenameext==$file_types_array[$x]) {
				$file_ext_allow = TRUE;
			}
		} // for
		if($file_ext_allow) {
			if($_FILES["$file"]["size"]<$max_file_size){
				$ieskom = array("?","&","="," ","+","-","#");
				$keiciam = array("","","","_","","","");
				$filename = str_replace($ieskom, $keiciam, $filename);
				if(is_file($upload_dir.$filename)) { $filename = time()."_".$filename; }
				move_uploaded_file($_FILES["$file"]["tmp_name"], $upload_dir.$filename);
				if (isimage($upload_dir.$filename)) { 
					trumb($upload_dir.$filename, 250, 250, "images/downloads/$filename.png");
					$pic = "$filename.png";
					//msg("Nusiųstas","Failas yra paveiksliukas: $filename sėkmingai apdorotas");
				}
				if (file_exists($upload_dir.$filename))	{
					mysql_query1("
					INSERT INTO `siuntiniai` (`pavadinimas`,`file`,`foto`,`apie`,`autorius`,`data`,`categorija`) 
					VALUES (".escape($_POST['pavadinimas']).",".escape($filename).",".escape($pic).",
					".escape($_POST['apie']).",".escape($_POST['nick']).", NOW(),".escape($_POST['kategorija']).")");
					
					if (mysql_affected_rows() > 0) { msg("Informacija","Failas sėkmingai patalpintas <h4>ir bus peržiūrėtas"); }
					else { klaida('Įkėlimo klaida', 'Dokumentas: <font color="#FF0000">'.$filename.'</font> nebuvo įkeltas'); }
				}
				else { klaida('Įkėlimo klaida', 'Dokumentas: <font color="#FF0000">'.$filename.'</font> nebuvo įkeltas'); }
			}
			else  { klaida('Įkėlimo klaida','<font color="#FF0000">'.$filename.'</font> dokumentas perdidelis'); }
		} // if
		else{ klaida('Įkėlimo klaida','<font color="#FF0000">'.$filename.'</font> dokumentas netinkamo plėtinio'); }
	}
}

function isImage($img) {
	//$img = str_replace(array("?","&","="),"",$img);
	list($owdt,$ohgt,$otype)=@getimagesize($img);
	  switch($otype) {
	   case 1: if (!function_exists('imagecreatefromgif')) { return false; } else { return true; } break;
	   case 2: if (!function_exists('imagecreatefromjpeg')) { return false; } else { return true; } break;
	   case 3: if (!function_exists('imagecreatefrompng')) { return false; } else { return true; } break;
	   case 7: if (!function_exists('imagecreatefromtif')) { return false; } else { return true; } break;
	   case 6: if (!function_exists('imagecreatefrombmp')) { return false; } else { return true; } break;
	   default: return false;
	  }
}

// Photo Gallery functions by CrappoMan
function constrainImage($width,$height,$max_width,$max_height){
	$img_width = '';
	$img_height = '';
	if (!$height||!$width||!$max_height||!$max_width) {
		return false;
	} elseif ($height>$max_height||$width>$max_width) {
		if ($height>$width) {
			if ($img_width>$max_width) {
				$img_width=$max_width;
				$img_height=round(($max_width*$max_height)/$img_width);
			} else {
				$img_width=round(($width*$max_height)/$height);
				$img_height=$max_height;
			}
		} else {
			if ($img_height>$max_height) {
				$img_width=round(($max_width*$max_height)/$img_height);
				$img_height=$max_height;
			} else {
				$img_width=$max_width;
				$img_height=round(($height*$max_width)/$width);
			}
		}
		return array('width'=>$img_width,'height'=>$img_height);
	} else {
		return array('width'=>$width,'height'=>$height);
	}
}

function trumb($origfile,$new_w,$new_h,$thumbfile) {
	global $gd;
	if ($gd != 'off') {
		list($owdt,$ohgt,$otype)=@getimagesize($origfile);
		  switch($otype) {
		   case 1:  $origimage=@imagecreatefromgif($origfile); break;
		   case 2:  $origimage=@imagecreatefromjpeg($origfile); break;
		   case 3:  $origimage=@imagecreatefrompng($origfile); break;
		   case 7:  $origimage=@imagecreatefromjpeg($origfile); break;
		   case 6:  $origimage=imagecreatefrombmp($origfile); break;
		   default: $origimage=@imagecreatefromjpeg($origfile); return;
		  }
		$origwidth=$owdt;
		$origheight=$ohgt;
		//echo "$owdt=\$owdt, $ohgt=\$ohgt";
		$size=constrainImage($origwidth,$origheight,$new_w,$new_h);
		if ($gd=="gd1") {
			$thumbimage=imagecreate($new_w,$new_h);
			$background=imagecolorallocate($thumbimage,255,255,255);
			imagefill($thumbimage,0,0,$background);
			$result=imagecopyresized($thumbimage, $origimage,round(($new_w-$size['width'])/2),round(($new_h-$size['height'])/2),0,0,$size['width'],$size['height'],$origwidth,$origheight);
		} else {
			$thumbimage=imagecreatetruecolor($new_w,$new_h);
			$background=imagecolorallocate($thumbimage,255,255,255);
			imagefill($thumbimage,0,0,$background);
			$result=imagecopyresampled($thumbimage, $origimage,round(($new_w-$size['width'])/2),round(($new_h-$size['height'])/2),0,0,$size['width'],$size['height'],$origwidth,$origheight);
		}
		touch($thumbfile);
		imageJPEG($thumbimage,$thumbfile);
	}
}

function ImageCreateFromBMP($filename) {
   if (! $f1 = fopen($filename,"rb")) return FALSE;
   $FILE = unpack("vfile_type/Vfile_size/Vreserved/Vbitmap_offset", fread($f1,14));
   if ($FILE['file_type'] != 19778) return FALSE;

   $BMP = unpack('Vheader_size/Vwidth/Vheight/vplanes/vbits_per_pixel'.
                 '/Vcompression/Vsize_bitmap/Vhoriz_resolution'.
                 '/Vvert_resolution/Vcolors_used/Vcolors_important', fread($f1,40));
   $BMP['colors'] = pow(2,$BMP['bits_per_pixel']);
   if ($BMP['size_bitmap'] == 0) $BMP['size_bitmap'] = $FILE['file_size'] - $FILE['bitmap_offset'];
   $BMP['bytes_per_pixel'] = $BMP['bits_per_pixel']/8;
   $BMP['bytes_per_pixel2'] = ceil($BMP['bytes_per_pixel']);
   $BMP['decal'] = ($BMP['width']*$BMP['bytes_per_pixel']/4);
   $BMP['decal'] -= floor($BMP['width']*$BMP['bytes_per_pixel']/4);
   $BMP['decal'] = 4-(4*$BMP['decal']);
   if ($BMP['decal'] == 4) $BMP['decal'] = 0;

   $PALETTE = array();
   if ($BMP['colors'] < 16777216)
   {
   $PALETTE = unpack('V'.$BMP['colors'], fread($f1,$BMP['colors']*4));
   }

   $IMG = fread($f1,$BMP['size_bitmap']);
   $VIDE = chr(0);

   $res = imagecreatetruecolor($BMP['width'],$BMP['height']);
   $P = 0;
   $Y = $BMP['height']-1;
   while ($Y >= 0)
   {
   $X=0;
   while ($X < $BMP['width'])
   {
     if ($BMP['bits_per_pixel'] == 24)
       $COLOR = unpack("V",substr($IMG,$P,3).$VIDE);
     elseif ($BMP['bits_per_pixel'] == 16)
     { 
       $COLOR = unpack("n",substr($IMG,$P,2));
       $COLOR[1] = $PALETTE[$COLOR[1]+1];
     }
     elseif ($BMP['bits_per_pixel'] == 8)
     { 
       $COLOR = unpack("n",$VIDE.substr($IMG,$P,1));
       $COLOR[1] = $PALETTE[$COLOR[1]+1];
     }
     elseif ($BMP['bits_per_pixel'] == 4)
     {
       $COLOR = unpack("n",$VIDE.substr($IMG,floor($P),1));
       if (($P*2)%2 == 0) $COLOR[1] = ($COLOR[1] >> 4) ; else $COLOR[1] = ($COLOR[1] & 0x0F);
       $COLOR[1] = $PALETTE[$COLOR[1]+1];
     }
     elseif ($BMP['bits_per_pixel'] == 1)
     {
       $COLOR = unpack("n",$VIDE.substr($IMG,floor($P),1));
       if    (($P*8)%8 == 0) $COLOR[1] =  $COLOR[1]        >>7;
       elseif (($P*8)%8 == 1) $COLOR[1] = ($COLOR[1] & 0x40)>>6;
       elseif (($P*8)%8 == 2) $COLOR[1] = ($COLOR[1] & 0x20)>>5;
       elseif (($P*8)%8 == 3) $COLOR[1] = ($COLOR[1] & 0x10)>>4;
       elseif (($P*8)%8 == 4) $COLOR[1] = ($COLOR[1] & 0x8)>>3;
       elseif (($P*8)%8 == 5) $COLOR[1] = ($COLOR[1] & 0x4)>>2;
       elseif (($P*8)%8 == 6) $COLOR[1] = ($COLOR[1] & 0x2)>>1;
       elseif (($P*8)%8 == 7) $COLOR[1] = ($COLOR[1] & 0x1);
       $COLOR[1] = $PALETTE[$COLOR[1]+1];
     }
     else
       return FALSE;
     imagesetpixel($res,$X,$Y,$COLOR[1]);
     $X++;
     $P += $BMP['bytes_per_pixel'];
   }
   $Y--;
   $P+=$BMP['decal'];
   }

   fclose($f1);

 return $res;
}
function trink($failas) {
	if (is_file($failas)) {
		if (@unlink($failas)) {
			msg("Ištrintas","Dokumentas <b>$failas</b> ištrintas!");
		}
		else { klaida("Klaida","Klaida trinant failą"); }
	}
}

function baitai($size,$digits=2,$dir=false) {
    $kb=1024; $mb=1024*$kb; $gb=1024*$mb; $tb=1024*$gb;
    if (($size==0)&&($dir)) { return " Nulis"; }
    elseif ($size<$kb) { return $size." Baitai"; }
    elseif ($size<$mb) { return round($size/$kb,$digits)." Kb"; }
    elseif ($size<$gb) { return round($size/$mb,$digits)." Mb"; }
    elseif ($size<$tb) { return round($size/$gb,$digits)." Gb"; }
    else { return round($size/$tb,$digits)." Tb"; }
}

    
$sql = mysql_query1("
SELECT
`s_kategorijos`.`pavadinimas` AS `kategorija`,
`siuntiniai`.`pavadinimas`,
`siuntiniai`.`foto`,
`siuntiniai`.`id`,
`siuntiniai`.`apie`,
`siuntiniai`.`data`,
`users`.`nick` AS `Nick`,
`users`.`id` AS `nick_id`,
`siuntiniai`.`file`
FROM
`s_kategorijos`
Inner Join `siuntiniai` ON `s_kategorijos`.`id` = `siuntiniai`.`categorija`
Inner Join `users` ON `siuntiniai`.`autorius` = `users`.`id`
ORDER BY
`siuntiniai`.`data` DESC
LIMIT 0, 50");

if (isset($_POST['action']) && !empty($_POST['action'])) {
	if ($_POST['action'] == "Sukurti" && !empty($_POST['kat_pav']) && !empty($_POST['kat_apie'])) {
		mysql_query1("INSERT INTO `s_kategorijos` (`pavadinimas`,`apie`) VALUES (".escape($_POST['kat_pav']).", ".escape($_POST['kat_apie']).")");
		if (mysql_affected_rows() > 0) {
			msg("Sukurta",smile("Viskas ok :)"));
		}
		else { klaida("Klaida",smile("Nu žinok nieko gero neyvyko :P")); }
	}
	if ($_POST['action'] == "Redaguoti" && !empty($_POST['kat_apie']) && !empty($_POST['kat_pav']) && !empty($_POST['kat_id']) && $_POST['kat_id'] > 0) {
		mysql_query1("UPDATE `s_kategorijos` SET `apie`=".escape($_POST['kat_apie']).", `pavadinimas`=".escape($_POST['kat_pav'])." WHERE (`id`=".escape($_POST['kat_id']).")");
		if (mysql_affected_rows() > 0) {
			msg("Atnaujinta",smile("Viskas ok :)"));
		}
		else { klaida("Klaida",smile("Nu žinok nieko gero neyvyko :P")); }
	}
	if ($_POST['action'] == "Trinti" && !empty($_POST['kategorija'])) {
		mysql_query1("DELETE FROM `s_kategorijos` WHERE (`id`=".escape($_POST['kategorija']).")");
		if (mysql_affected_rows() > 0) {
			msg("Ištrinta",smile("Viskas ok :) kategorija sėkmingai ištrinta"));
		}
		else { klaida("Klaida",smile("Nu žinok nieko gero neyvyko :P")); }
	}
	if ($_POST['action'] == "Redaguoti" && !empty($_POST['kategorija']) && $_POST['kategorija'] > 0) {
		$kat = mysql_fetch_assoc(mysql_query1("SELECT * FROM `s_kategorijos` WHERE `id`=".escape((int)$_POST['kategorija'])." LIMIT 1"));
		
		if (mysql_affected_rows() > 0) {
			//msg("Atnaujinta",smile("Viskas ok :)"));
		}
		else { klaida("Klaida",smile("Nu žinok nieko gero neyvyko :P")); }
	}
}
?>


<p>
  <input name="1" type="button" id="1" value="Peržiūrėti" />
  <input name="2" type="button" id="2" value="Redaguoti kategoriją" />
  <input name="3" type="button" id="3" value="Sukurti kategoriją" />
  <input name="4" type="button" id="4" value="Naujas siuntinys" />
</p>
<table width="100%" border="0" cellpadding="0" cellspacing="0" class="vidus">
  <tr class="title">
    <th width="3%">Nr.</th>
    <th width="31%">Failas</th>
    <th width="34%">Kategorija</th>
    <th width="32%">Veiksmas</th>
  </tr>
<?
while ($row = mysql_fetch_assoc($sql)) { ?>
  <tr class="sarasas">
    <td><?=$row['id']?></td>
    <td><a href="?id,6;v,<?=$row['id']?>" title="header=[<?=$row['pavadinimas']?>] body=[<br/><center><img src='images/downloads/<?=$row['foto']?>'></center><p>Autorius: <b><?=$row['Nick']?></b><br/>Data: <b><?=$row['data']?></b><br/>Dydis:<b> <?=baitai(filesize('downloads/'.$row['file'].''))?></b><br/>Aprašymas: <br/><i><?=smile(wrap1($row['apie'],35))?></i></p>] cssbody=[sarasas] cssheader=[title] fade=[on]"><?=$row['pavadinimas']?></a></td>
    <td><?=$row['kategorija']?></td>
    <td><a href="<?=url("d,".$row['id']."")?>">[d]</a> <a href="<?=url("r,".$row['id']."")?>">[r]</a></td>
  </tr>
  <? } ?>
</table>

<form action="?id,46;a,13" method="post" enctype="multipart/form-data" name="form1" id="form1">
  <table width="300" border="0" align="center" cellpadding="3" cellspacing="0" class="vidus">
    <tr class="title">
      <th colspan="2" align="left" nowrap="nowrap">Naujas siuntinys </th>
    </tr>
    <tr class="vidus">
      <td align="right" nowrap="nowrap" class="sarasas">Siuntinio pavadinimas: </td>
      <td class="sarasas"><input name="pavadinimas" type="text" maxlength="100" style="width:200px" /></td>
    </tr>
    <tr class="vidus">
      <td align="right" nowrap="nowrap" class="sarasas">Siuntinio failas: </td>
      <td class="sarasas"><input type="file" name="file" style="width:200px" /></td>
    </tr>
    <tr class="vidus">
      <td align="right" nowrap="nowrap" class="sarasas">Siuntinio paveiksliukas: </td>
      <td class="sarasas"><input type="file" name="pic" style="width:200px" /></td>
    </tr>
    <tr class="vidus">
      <td align="right" nowrap="nowrap" class="sarasas">Siuntinio aprašymas: </td>
      <td class="sarasas"><textarea name="apie" rows="6" style="width:200px"></textarea></td>
    </tr>
    <tr class="vidus">
      <td align="right" nowrap="nowrap" class="sarasas">Kategorija:</td>
      <td class="sarasas"><select name="kategorija">
        <? $sql = mysql_query1("SELECT * FROM `s_kategorijos`");
	  while ($row = mysql_fetch_assoc($sql)) { ?>
        <option value="<?=$row['id']?>">
          <?=$row['pavadinimas']?>
          </option>
        <? } unset($row,$sql); ?>
      </select></td>
    </tr>
    <tr class="vidus">
      <td align="right" nowrap="nowrap" class="sarasas">Autorius:</td>
      <td class="sarasas"><select name="nick">
        <? $sql = mysql_query1("SELECT id, nick FROM `users`");
	  while ($row = mysql_fetch_assoc($sql)) { ?>
        <option value="<?=$row['id']?>" <?=($_SESSION['username']==$row['nick'])?'selected="selected"':''?>>
          <?=$row['nick']?>
          </option>
        <? } unset($row,$sql); ?>
      </select></td>
    </tr>
    <tr class="vidus">
      <td align="right" nowrap="nowrap" class="sarasas">&nbsp;</td>
      <td class="sarasas"><input type="submit" name="Submit" value="Siųsti" /></td>
    </tr>
  </table>
</form>
<!--
Array
(
    [kat_pav] => df
    [kat_apie] => dfg
    [action] => Sukurti
)
-->
<form action="?id,46;a,13" method="post" enctype="multipart/form-data" name="Naujas" id="Naujas">
  <table width="300" border="0" align="center" cellpadding="3" cellspacing="0" class="vidus">
    <tr class="title">
      <th colspan="2" align="left" nowrap="nowrap"><?=($_POST['action'] == "Redaguoti")?'Redaguoti':'Sukurti naują'?> kategoriją</th>
    </tr>
    <tr class="vidus">
      <td align="right" nowrap="nowrap" class="sarasas">Kategorijos pavadinimas: </td>
      <td class="sarasas"><input name="kat_pav" type="text" id="kat_pav" style="width:200px" value="<?=input($kat['pavadinimas'])?>" maxlength="100" /></td>
    </tr>
    <tr class="vidus">
      <td align="right" nowrap="nowrap" class="sarasas">Kategorijos aprašymas: </td>
      <td class="sarasas"><textarea name="kat_apie" rows="6" id="kat_apie" style="width:200px"><?=input($kat['apie'])?></textarea></td>
    </tr>
    <tr class="vidus">
      <td align="right" nowrap="nowrap" class="sarasas"><input name="kat_id" type="hidden" id="kat_id" value="<?=input($kat['id'])?>" /></td>
      <td class="sarasas"><input name="action" type="submit" id="action" value="<?=($_POST['action'] == "Redaguoti")?'Redaguoti':'Sukurti'?>" /></td>
    </tr>
  </table>
</form>
<form action="?id,46;a,13" method="post" enctype="multipart/form-data" name="redaguoti" id="redaguoti">
  <table width="300" border="0" align="center" cellpadding="3" cellspacing="0" class="vidus">
    <tr class="title">
      <th colspan="2" align="left" nowrap="nowrap">Redaguoti kategoriją </th>
    </tr>

    <tr class="vidus">
      <td align="right" nowrap="nowrap" class="sarasas">Pasirink kategoriją :</td>
      <td class="sarasas"><select name="kategorija" id="kategorija">
          <? $sql = mysql_query1("SELECT * FROM `s_kategorijos`");
	  while ($row = mysql_fetch_assoc($sql)) { ?>
          <option value="<?=$row['id']?>">
          <?=$row['pavadinimas']?>
          </option>
          <? } unset($row,$sql); ?>
      </select></td>
    </tr>
    <tr class="vidus">
      <td align="right" nowrap="nowrap" class="sarasas">&nbsp;</td>
      <td class="sarasas"><input name="action" type="submit" id="action" value="Redaguoti" />
      <input name="action" type="submit" id="action" value="Trinti" /></td>
    </tr>
  </table>
</form>
<p>&nbsp;</p>
<p>&nbsp;</p>
